package com.laiyuezs.sdk2x;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.bouncycastle.asn1.pkcs.PrivateKeyInfo;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.openssl.PEMParser;
import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter;
import org.bouncycastle.util.encoders.Hex;
import sun.misc.BASE64Decoder;

import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.security.PrivateKey;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

/**
 * @author : 州长在手 2021/1/5 下午2:05
 */
public class InUtils {


  public static final   int SUCCESS = 200;
  public  static final int ERROR = 9999;
    /**
     * 将日期转换为字符串
     *
     * @param date date日期
     *
     * @return 日期字符串
     */
    public static String parseDateFormat(Date date) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss", Locale.CHINA);
            return sdf.format(date);
        } catch (Exception ex) {
            return "";
        }
    }
    public static JSONObject getSuccess(JSON json) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", 200);
        jsonObject.put("data", json);
        return jsonObject;
    }

     public static PrivateKey getPrivateKeyFromBytes(String data) throws IOException {
        final Reader pemReader = new StringReader(data);
        final PrivateKeyInfo pemPair;
        try (PEMParser pemParser = new PEMParser(pemReader)) {
            pemPair = (PrivateKeyInfo) pemParser.readObject();
        }
        return new JcaPEMKeyConverter().setProvider(BouncyCastleProvider.PROVIDER_NAME).getPrivateKey(pemPair);

    }

    public static JSONObject RespError(String data, String txid){
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", InUtils.ERROR);
        jsonObject.put("data",data);
        jsonObject.put("txid",txid);
        return jsonObject;
    }

    public static JSONObject RespSuccess(String data, String txid){
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", InUtils.SUCCESS);
        jsonObject.put("data",data);
        jsonObject.put("txid",txid);
        return jsonObject;
    }

    public static byte[] base64Str2Byte(String str) throws IOException {
        return new BASE64Decoder().decodeBuffer(str);
    }

    public static byte[] hexStr2Byte(String str)  {
        return  Hex.decode(str);
    }



    /**
     * 读取 InputStream 到 String字符串中
     */
    public static String readStream(InputStream in) {

        try {
            //<1>创建字节数组输出流，用来输出读取到的内容
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            //<2>创建缓存大小
            byte[] buffer = new byte[1024]; // 1KB
            //每次读取到内容的长度
            int len = -1;
            //<3>开始读取输入流中的内容
            while ((len = in.read(buffer)) != -1) { //当等于-1说明没有数据可以读取了
                baos.write(buffer, 0, len);   //把读取到的内容写到输出流中
            }
            //<4> 把字节数组转换为字符串
            String content = baos.toString();
            //<5>关闭输入流和输出流
            in.close();
            baos.close();
            //<6>返回字符串结果
            return content;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

    }

    public static byte[] readStream2byte(InputStream in) {

        try {
            //<1>创建字节数组输出流，用来输出读取到的内容
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            //<2>创建缓存大小
            byte[] buffer = new byte[1024]; // 1KB
            //每次读取到内容的长度
            int len = -1;
            //<3>开始读取输入流中的内容
            while ((len = in.read(buffer)) != -1) { //当等于-1说明没有数据可以读取了
                baos.write(buffer, 0, len);   //把读取到的内容写到输出流中
            }
            //<4> 把字节数组转换为字符串
            //String content = baos.toString();
            byte[] content = baos.toByteArray();
            //<5>关闭输入流和输出流
            in.close();
            baos.close();
            //<6>返回字符串结果
            return content ;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

    }

    public static void writeStream(String fileName, String content) {

        try {

            // 打开一个随机访问文件流，按读写方式
            RandomAccessFile randomFile = new RandomAccessFile(fileName, "rw");
            // 文件长度，字节数
            long fileLength = randomFile.length();
            // 将写文件指针移到文件尾。
            randomFile.seek(fileLength);
            randomFile.writeBytes(content);
            randomFile.close();
        } catch (IOException e) {

            e.printStackTrace();

        }

    }


    public static void writeStream(InputStream is,String fileName) throws IOException{
        BufferedInputStream in=null;
        BufferedOutputStream out=null;
        in=new BufferedInputStream(is);
        out=new BufferedOutputStream(new FileOutputStream(fileName));
        int len=-1;
        byte[] b=new byte[1024];
        while((len=in.read(b))!=-1){
            out.write(b,0,len);
        }
        in.close();
        out.close();
    }


    /**
     * 根据文件地址返回文件的字节数组
     * @param filename
     * @return
     * @throws IOException
     */
    public static byte[] toByteArray(String filename) throws IOException {
        File f = new File(filename);
        if (!f.exists()) {
            throw new FileNotFoundException(filename);
        }
        FileChannel channel = null;
        FileInputStream fs = null;
        try {
            fs = new FileInputStream(f);
            channel = fs.getChannel();
            ByteBuffer byteBuffer = ByteBuffer.allocate((int) channel.size());
            while ((channel.read(byteBuffer)) > 0) {
                // do nothing
                // System.out.println("reading");
            }
            return byteBuffer.array();
        } catch (IOException e) {
            throw e;
        } finally {
            try {
                channel.close();
            } catch (IOException e) {
                //
            }
            try {
                fs.close();
            } catch (IOException e) {
               //
            }
        }
    }

}
